﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperJoe.Framework.UnitOfWorkSql;
using WWX.Dto.Search;
using WWX.MemberPortal.IDAL;
using WWX.Model;

namespace WWX.MemberPortal.DAL
{
    public class OrderDAL : BaseDAL, IOrderDAL
    {
        public OrderDAL(IUnitOfWork uow) : base(uow)
        {
        }

        public List<Order> GetPageList(OrderSearch search, int pageNo, int pageSize, out int total)
        {
            List<Order> retList = null;
            Dictionary<string, object> parameters = null;
            var whereSql = GenerateWhereSql(search, out parameters);

            string totalSql = "select count(1) from orders where 1=1 " + whereSql;
            total = this.GetCount(totalSql, parameters);
            if (total != 0)
            {
                var pagingSql = "select * from orders where 1=1  " + whereSql + " order by date desc limit " + (pageNo - 1) + "," + pageSize;

                retList = this.GetModels<Order>(pagingSql, parameters);

            }

            return retList ?? new List<Order>();
        }

        private string GenerateWhereSql(OrderSearch search, out Dictionary<string, object> parameters)
        {
            parameters = this.CreateParameters();
            string sql = "";

            if (search.EndDate.HasValue)
            {
                sql += " and date<'" + search.EndDate.Value.AddDays(1).Date.ToString() + "'";
            }

            if (search.StartDate.HasValue)
            {
                sql += " and date>='" + search.StartDate.Value.Date.ToString() + "'";
            }

            if (search.Status.HasValue)
            {
                sql += " and status=" + (int)search.Status.Value;
            }

            if (search.ProductInfo.IsNotNullOrWhiteSpace())
            {
                sql += " and productinfo like ?productinfo";
                parameters.Add("productinfo", $"%{search.ProductInfo}%");
            }

            if (search.LogisticsInfo.IsNotNullOrWhiteSpace())
            {
                sql += " and logisticsinfo like ?logisticsinfo";
                parameters.Add("logisticsinfo", $"%{search.LogisticsInfo}%");
            }

            if (search.IsDeducted.HasValue)
            {
                sql += " and isdeducted=?isdeducted";
                parameters.Add("isdeducted", search.IsDeducted.Value);
            }

            sql += " and memberid=?memberid";
            parameters.Add("memberid", search.MemberId);

            return sql;
        }
    }
}
